package utils

import (
	"fmt"
	"sync"
	"time"
)

// Statistics 网络数据统计器
type Statistics struct {
	mutex sync.RWMutex

	// 基础统计
	BytesSent       int64
	BytesReceived   int64
	PacketsSent     int64
	PacketsReceived int64

	// 连接统计
	TotalConnections  int64
	ActiveConnections int64
	MaxConnections    int64

	// 时间统计
	StartTime    time.Time
	LastActivity time.Time

	// 速率统计
	LastResetTime     time.Time
	LastBytesSent     int64
	LastBytesReceived int64

	// 历史记录（最近10个数据点）
	History []StatSnapshot
}

// StatSnapshot 统计快照
type StatSnapshot struct {
	Timestamp     time.Time
	BytesSent     int64
	BytesReceived int64
	SendRate      float64 // 字节/秒
	ReceiveRate   float64 // 字节/秒
	ActiveConns   int64
}

// NewStatistics 创建新的统计实例
func NewStatistics() *Statistics {
	now := time.Now()
	return &Statistics{
		StartTime:     now,
		LastActivity:  now,
		LastResetTime: now,
		History:       make([]StatSnapshot, 0, 10),
	}
}

// RecordSent 记录发送的数据
func (s *Statistics) RecordSent(bytes int64) {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	s.BytesSent += bytes
	s.PacketsSent++
	s.LastActivity = time.Now()
}

// RecordReceived 记录接收的数据
func (s *Statistics) RecordReceived(bytes int64) {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	s.BytesReceived += bytes
	s.PacketsReceived++
	s.LastActivity = time.Now()
}

// RecordConnection 记录新连接
func (s *Statistics) RecordConnection() {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	s.TotalConnections++
	s.ActiveConnections++
	if s.ActiveConnections > s.MaxConnections {
		s.MaxConnections = s.ActiveConnections
	}
	s.LastActivity = time.Now()
}

// RecordDisconnection 记录断开连接
func (s *Statistics) RecordDisconnection() {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	if s.ActiveConnections > 0 {
		s.ActiveConnections--
	}
	s.LastActivity = time.Now()
}

// GetCurrentStats 获取当前统计信息
func (s *Statistics) GetCurrentStats() StatSnapshot {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	now := time.Now()
	duration := now.Sub(s.LastResetTime).Seconds()

	var sendRate, receiveRate float64
	if duration > 0 {
		sendRate = float64(s.BytesSent-s.LastBytesSent) / duration
		receiveRate = float64(s.BytesReceived-s.LastBytesReceived) / duration
	}

	return StatSnapshot{
		Timestamp:     now,
		BytesSent:     s.BytesSent,
		BytesReceived: s.BytesReceived,
		SendRate:      sendRate,
		ReceiveRate:   receiveRate,
		ActiveConns:   s.ActiveConnections,
	}
}

// GetTotalStats 获取总体统计信息
func (s *Statistics) GetTotalStats() (int64, int64, int64, int64, int64, int64, int64, time.Duration) {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	duration := time.Since(s.StartTime)
	return s.BytesSent, s.BytesReceived, s.PacketsSent, s.PacketsReceived,
		s.TotalConnections, s.ActiveConnections, s.MaxConnections, duration
}

// GetRates 获取当前传输速率
func (s *Statistics) GetRates() (float64, float64) {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	now := time.Now()
	duration := now.Sub(s.LastResetTime).Seconds()

	if duration <= 0 {
		return 0, 0
	}

	sendRate := float64(s.BytesSent-s.LastBytesSent) / duration
	receiveRate := float64(s.BytesReceived-s.LastBytesReceived) / duration

	return sendRate, receiveRate
}

// TakeSnapshot 创建统计快照并添加到历史记录
func (s *Statistics) TakeSnapshot() StatSnapshot {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	snapshot := s.getCurrentStatsUnsafe()

	// 添加到历史记录
	s.History = append(s.History, snapshot)

	// 保持最多10个历史记录
	if len(s.History) > 10 {
		s.History = s.History[1:]
	}

	// 重置速率计算基点
	s.LastResetTime = snapshot.Timestamp
	s.LastBytesSent = s.BytesSent
	s.LastBytesReceived = s.BytesReceived

	return snapshot
}

// getCurrentStatsUnsafe 获取当前统计信息（不加锁）
func (s *Statistics) getCurrentStatsUnsafe() StatSnapshot {
	now := time.Now()
	duration := now.Sub(s.LastResetTime).Seconds()

	var sendRate, receiveRate float64
	if duration > 0 {
		sendRate = float64(s.BytesSent-s.LastBytesSent) / duration
		receiveRate = float64(s.BytesReceived-s.LastBytesReceived) / duration
	}

	return StatSnapshot{
		Timestamp:     now,
		BytesSent:     s.BytesSent,
		BytesReceived: s.BytesReceived,
		SendRate:      sendRate,
		ReceiveRate:   receiveRate,
		ActiveConns:   s.ActiveConnections,
	}
}

// GetHistory 获取历史记录
func (s *Statistics) GetHistory() []StatSnapshot {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	// 返回副本
	history := make([]StatSnapshot, len(s.History))
	copy(history, s.History)
	return history
}

// Reset 重置统计信息
func (s *Statistics) Reset() {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	now := time.Now()
	s.BytesSent = 0
	s.BytesReceived = 0
	s.PacketsSent = 0
	s.PacketsReceived = 0
	s.TotalConnections = 0
	s.ActiveConnections = 0
	s.MaxConnections = 0
	s.StartTime = now
	s.LastActivity = now
	s.LastResetTime = now
	s.LastBytesSent = 0
	s.LastBytesReceived = 0
	s.History = make([]StatSnapshot, 0, 10)
}

// GetUptime 获取运行时间
func (s *Statistics) GetUptime() time.Duration {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	return time.Since(s.StartTime)
}

// GetLastActivity 获取最后活动时间
func (s *Statistics) GetLastActivity() time.Time {
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	return s.LastActivity
}

// FormatBytes 格式化字节数显示
func FormatBytes(bytes int64) string {
	const unit = 1024
	if bytes < unit {
		return fmt.Sprintf("%d B", bytes)
	}
	div, exp := int64(unit), 0
	for n := bytes / unit; n >= unit; n /= unit {
		div *= unit
		exp++
	}
	return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
}

// FormatRate 格式化传输速率显示
func FormatRate(bytesPerSecond float64) string {
	return FormatBytes(int64(bytesPerSecond)) + "/s"
}

// FormatDuration 格式化持续时间显示
func FormatDuration(d time.Duration) string {
	if d < time.Minute {
		return fmt.Sprintf("%.1fs", d.Seconds())
	}
	if d < time.Hour {
		return fmt.Sprintf("%.1fm", d.Minutes())
	}
	if d < 24*time.Hour {
		return fmt.Sprintf("%.1fh", d.Hours())
	}
	return fmt.Sprintf("%.1fd", d.Hours()/24)
}
